简体   繁体   中英

Issue in caching using coffeescript

I've this script

class Raffler.Views.EntriesIndex extends Backbone.View

    div: $('#input')

    initialize: ->

       console.log @div.val()

As you can see this is a backbone's view.

I would like to cache $('#div') into a variable and call it. See the console.log @div.val() .

But this seems not working..

Using normal javascript I'd write something like this:

var ToDoView = Backbone.View.extend({
    div : $('#input'),
    initialize: function(){
         console.log(this.div.val());
    }
})

And this is working fine. Where I'm going wrong with coffeescript?

There are some differences in how Coffeescript classes work and Backbone's extend mechanism work, which could be the issue you are running into. But I'm guessing that is not the issue here. There could be differences in exactly when and where you are running this code as well. If you put the javascript code in the same place where you are executing your coffeescript code, does it then work ok? And on a related note, what exacly is the problem, ie what error messages are you getting? Is @div initialized at all?

It's likely the $("#input") element hasn't been loaded at the moment your code runs.

The problem with caching the value in the class is that the class is most likely being defined outside the jQuery.ready callback (before the DOM has finished loading) so at the moment your class sets $("#input") as @div jQuery doesn't actually find that element.

You could set @div in the initialize function since that will most likely be called after the DOM has loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM