我正在使用 bbjs 开发我的第一个应用程序,经过 10 个教程和无尽的资源之后,我试图提出我的代码设计。
我问视图和模板的最佳实践是什么。还有一个我正在努力解决的事件问题。据我了解,视图负责一个元素及其内容(以及其他子视图)。为了使代码易于管理、可测试等。元素/模板将在创建时传递给视图。在我的应用程序 Imho 中,视图应该包含模板,因为可见元素有许多“状态”和每个状态的不同模板。当状态发生变化时,我想最好创建一个新视图,但是,视图是否可以用新元素更新自己?
App.Box = Backbone.Model.extend({
    defaults: function() {
        return {
            media: "http://placehold.it/200x100",
            text: "empty...",
            type: "type1"
        };
    }
});
App.BoxView = Backbone.View.extend({
    template: {},
    templates: {
            "type1": template('appboxtype1'),
            "type2": template('appboxtype2')
    },
    events: {
      'click .button': 'delete'
    },
    initialize: function(options) {
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'destroy', this.remove);
        this.render();
    },
    render: function() {
        this.template = this.templates[ this.model.get("type") ];
        // first method
        this.$el.replaceWith(  $($.parseHTML(this.template(this)))  );
        this.$el.attr("id", this.model.cid);
        // second method
        var $t_el = this.$el;
        this.setElement( $($.parseHTML(this.template(this))) );
        this.$el.attr("id", this.model.cid);
        $t_el.replaceWith(  this.$el  );
        this.delegateEvents();
        //$('#'+this.model.cid).replaceWith(  $(g.test.trim()) );
        //! on the second render the events are no longer bind, deligateEvents doesn't help
        return this;
    },
    // get values
    text: function() { return this.model.get('text');  },
    media: function() { return this.model.get('media');  },
    delete: function() {
        this.model.destroy();
    }
});
谢谢!:)