0

So I know there are many ways for doing things in Backbone, but since I don't have the vast experience of many on here, I would like advice regarding a best approach.

I have a basic CRUD app where I have a form for adding data and a form for editing data, which are essentially the same. And actually are attached to the same DOM element.

So I could include the two forms into one view and serve the appropriate template, depending on whether the view has a model or not. Something like this:

var AddEditView = Backbone.View.extend ({
el: $("#add"),
template: $("editTemplate").html();
render: function() {
    if (this.model) {
        var theTmp = _.template(this.template)
        this.$el.html(theTmp(this.model.toJSON()));
    }
    else {
        var theTmp = _.template($("#addTemplate").html());
        this.$el.html(theTmp);
    }
},

}); I think this would work however I might run into some sticky issues with any events (i.e. events being bound twice).

Or I could create two completely separate views that would be attached to the same dom element and would toggle back and forth depending on the app state (way more lines of code).

What would you all recommend in this situation. Is more logic in a view better or more lines of code and less logic in views?

4

1 回答 1

2

假设无论您是创建新模型还是编辑现有模型,这些字段都是相同的,我建议只有一个视图和一个模板。当您实例化视图时,如果您正在创建一个新模型,只需实例化一个新模型并将其传递给视图。否则,通过现有模型。

var AddEditView = Backbone.View.extend ({
    render: function() {
        var theTmp = _.template(this.template)
        this.$el.html(theTmp(this.model.toJSON()));
    },
    someSaveEvent: function() {
        this.model.save(); // This will POST if the model isNew() or PUT otherwise
    }
});

var model = new Model(); // If you're creating a new model

var addEditView = new AddEditView({
    model: model
});
于 2013-01-10T22:45:39.550 回答