【问题标题】:error coming while making a view in backbone.js在backbone.js中创建视图时出现错误
【发布时间】:2011-05-16 12:08:59
【问题描述】:

这里我想在backbone.js中做一个视图

// The DOM element for a User item...
    var UserView = Backbone.View.extend({
        //... is a list tag.
        tagName:  "li",
         // Cache the template function for a single item.
        template: _.template($('#tmpl_occupant').html()),

        // a one-to-one correspondence between a **User** and a **UserView** in this
        // app, we set a direct reference on the model for convenience.
        initialize: function() {

            _.bindAll(this, 'render', 'close');
            this.model.bind('change', this.render);
            this.model.view = this;
        },
        // Re-render the contents of the User item.
        render: function() {
            $(this.el).html(this.template(this.model.toJSON()));
            return this;
        }
    });

我把这个视图代码放在 user.js 中,当 index.html 加载它时,它会被调用并给出错误

str is null
http://myserver/rahul/js/underscore-1.1.3.js
Line 675

我认为这是因为删除此行时没有出现错误

  template: _.template($('#tmpl_occupant').html()),


<script type="text/html" id="tmpl_occupant">
    <%=user.username%> is in <%=gib.name%> (<%=channel%>)
    </script>

我认为这是因为执行此行时 index.html 没有完全加载。所以它不适合 tmpl_occupant ,我该怎么做才能解决这个问题。

【问题讨论】:

    标签: jquery templates backbone.js


    【解决方案1】:

    我能做些什么来解决这个问题?

    首先,您可以将初始化脚本移动到 HTML 文档的底部。这确保了它会在所有 HTML 加载完成后运行。

    否则,您可以将初始化代码包装在 $(document).ready() 块中,这将确保文档已完全加载并且 HTML 可用。我的代码如下所示:

    ApplicationController = Backbone.Controller.extend({
        /* router code here */
    });
    
    $(document).ready(function() {
        myapp = new ApplicationController()
    });
    

    这使用 jQuery 的 DOM 就绪事件来确保在运行第一行客户端代码之前一切就绪。

    【讨论】:

    • 另外你必须在初始化函数中初始化模板。
    • 朱利安:为什么? Rahul 使用 underscore.js 模板;除了从 DOM 中拉出到 HTML 字符串中之外,它们不需要太多初始化。如果模板嵌入到文档中,就像我经常使用 script 标签一样,那么它会在 DOM 树处于活动状态时出现。
    • 他的模板属性正在查看 DOM 以加载模板。
    • 啊,是的,你是对的。对不起。我有将模板放在代码调用之前的好习惯。
    【解决方案2】:

    通过直接传递字符串而不是 jquery 引用来完成。 或

    http://documentcloud.github.com/underscore/#template 更好的解决方案是编译模板并将模板传递给视图实例。

    【讨论】:

    • 我没有做对。我怎样才能传递一个字符串而不是 jquery 引用?我也在我的代码模板上使用它:_.template($("tpl-item-list").html()),
    猜你喜欢
    • 2012-01-18
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多