Backbone.js view instance variables?

拟墨画扇 提交于 2019-12-03 10:53:31

Your view_templates instance variable is fine (and a good idea as well). You just have to be sure that you're using the right this inside your $.get() callback and inside your tmpls.each() call. I think you want your initialize to look more like this:

initialize: function() {
    this.view_templates = { };

    var _this = this;
    $.get('js/Test2Templates.tpl', function(doc) {
        var tmpls = $(doc).filter('template');
        tmpls.each(function() {
            _this.view_templates[this.id] = $.jqotec($.unescapeHTML(this.innerHTML));
        });
    });
},

I'm not sure which this.id you want inside the tmpls.each() but I'm guessing that you want the DOM id attribute from the current template so I left it as this.id.

The this.view_templates assignment in your constructor (initialize) is needed because you presumably want each instance of the view to have its own copy of the array. Creating a new view instance doesn't do a deep copy of the the view so if you just have:

MessageView = Backbone.View.extend({
    view_templates: {},
    // ...

then all the instances will end up sharing the same view_templates object and view_templates will behave more like a class variable than an instance variable.

You can specify your instance variables in the view definition (i.e. the Backbone.View.extend() call) as a form of documentation but you will want to initialize any of them that should behave as an instance variable in your initialize method; read-only or "class variables" like events can be left as part of the view's definition.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!