Trying to improve my coding styles I\'ve tried different solutions but I can\'t figure out what is the best.
I\'ve started putting JavaScript inside my views but I don\'
Here's my methods on ASP.NET MVC3 to complete the @weirdlover answer, one thing he's missing is the JSON encoding which is quite important when you want to safely inject data in js.
If the data is not too big and can be logically attached to a DOM element, I use one (or several) data-attribute (don't require a jQuery plugin and leave the css class pretty) and a css class to find the elements from jQuery.
Stupid example:
HTML:
COFFEESCRIPT:
class TextWidget
constructor: (@element) ->
@el = $ @element
@options = @el.data 'options'
@input = @el.find 'input'
@input.change @update
update: =>
value = @input.val()
$.post @options.url,
value: value
, -> alert 'text saved'
$ ->
new TextWidget element for element in $('.text-widget').get()
A little gotcha with Json.Encode and jQuery.data: if you use it on a simple string, you will get a quoted string in javascript: $().data('strattribute') == ' "hello" '. Just use Html.Encode in that case.
Anyway I prefer to use a single attibute with an anonymous object I build in the controller, it's easier to maintain: data-options="@Json.Encode(Model.Options)".
If there is a lot of data, like a list of objects I will turn to ViewModels for knockoutjs, I use a and var data = @(Html.Raw(Json.Encode(Model.MyData)));.
I also use namespacing and closures to avoid poluting the global object.