javascript - Backbonejs 查看 self 模板replaceWith 和事件

标签 javascript jquery backbone.js

我正在使用 bbjs 开发我的第一个应用程序,经过 10 个教程和无尽的资源后,我正在尝试提出我的代码设计。

我问 View 和模板的最佳实践是什么。还有一个我正在努力解决的事件问题。 据我了解, View 负责一个元素及其内容(以及其他 subview )。 为了使代码可管理、可测试等,元素/模板将在创建时传递到 View 。 在我的应用程序中,恕我直言, View 应该包含模板,因为可见元素有许多“状态”,并且每个状态都有不同的模板。 当状态发生变化时,我想最好创建一个新 View ,但是, View 是否可以使用新元素更新自身?

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();
    }
});

谢谢! :)

最佳答案

不要尝试替换 View 的根元素 ($el),只需替换其内容即可。

this.$el.html(this.template(this));

那么事件应该仍然有效。

关于javascript - Backbonejs 查看 self 模板replaceWith 和事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14659597/

相关文章:

javascript - 了解 Backbone.js 概念

jquery - 主干/下划线 : How to get index of a model inside render?

javascript - 从右到左的可折叠面板

javascript - 如何在 Monaco 编辑器中获得 JQuery 代码完成?

javascript - 在 three.js 中向对象(白色圆圈)添加文本

javascript - "Error: Module name ' 下划线 ' has not been loaded yet for context: _"有时仅在 Firefox 上出现

c# - 如何从 C# 用户控件中的 jquery 检索值?

javascript - 在 javascript 中生成表单时出现问题 [HTML5]

javascript - 代码触发事件时如何使用.submit()

javascript - 事件发生后 knockout JS textInput