theironcook / Backbone.ModelBinder

Simple, flexible and powerful Model-View binding for Backbone.
1.42k stars 159 forks source link

Something similar to Marionette.Behaviors #190

Open crebuh opened 10 years ago

crebuh commented 10 years ago

Hello!

I'm heavily using the Backbone.Modelbinder in my views. Often i reuse bindings in several views. For example i use this binding in several views:

            description: {
                selector: '[name="description"]',
                elAttribute: 'html',
                converter: uiHelper.fillPlaceholder
            }

I searching a similar solution like Marionette.Behaviors, there you can define a set of interactions (events) and mix it into the views. Is there a similar possibilty to mix in a "behaviour" for certain bindnigs like

 description : descriptionBinding

an descriptionBinding is an object with

                selector: '[name="description"]',
                elAttribute: 'html',
                converter: uiHelper.fillPlaceholder

Does anybody has an idea how to do this?

platinumazure commented 9 years ago

What are you trying to do exactly that can't be done with the existing functionality?

If you want to make sure that a binding is copied into bindings objects in every one of you views, you could create a new base class and mix in the behavior that way:

var BaseBindingView = Backbone.View.extend({
    initialize: function (options) {
        this.modelBinder = new Backbone.ModelBinder();
    },
    render: function () {
        this.modelBinder.bind(this.model, this.$el, _.result(this, "bindings"));
    },
    bindings: function () {
        // Return your common bindings here
        return { description: [{ /* etc. */ }] };
    }
});

And then in your deriving classes:

var MyActualView = BaseBindingView.extend({
    bindings: function () {
        var baseBindings = BaseBindingView.prototype.bindings.call(this);
        return _.extend(baseBindings, {
            // Add other bindings specific to just this view
        });
    }
});

Would that work? The only time I could see that being a problem is if you already have a base view; but even then, after defining the view, you could still possibly mix in the other bindings using _.extend on the view prototype, or something like that.