简体   繁体   English

在Backbone js中提取逻辑

[英]Abstracting logic in Backbone js

I'm developing a Backbone application using Marionette and I need some help to organize the logic in the code. 我正在使用Marionette开发Backbone应用程序,我需要一些帮助来组织代码中的逻辑。

Currently I have a few views where I handle really similar logic, I want to abstract this to avoid repetition: 目前我有几个视图,我处理非常相似的逻辑,我想抽象这个,以避免重复:

View1 视图1

onRender: function() {
    var pluginData = this.$("selector1").plugin();
    var pluginResult = this.handlePluginData(pluginData);
    this.doSomethingWithResult1(pluginResult);
}

View2 视图2

onRender: function() {
    var pluginData = this.$("selector2").plugin();
    var pluginResult = this.handlePluginData(pluginData);
    this.doSomethingWithResult2(pluginResult);
}

Etc 等等

Note: handlePluginData do the same thing, doSomethingWithResultN it's different but can be abstracted with a few params. 注意: handlePluginData做同样的事情, doSomethingWithResultN它不同但可以用一些参数抽象。

So the questions are: 所以问题是:

  • How should I abstract this?, I thought of extending from a BaseView class and adding the logic there, but I don't know if there's a better way. 我应该如何抽象?,我想从BaseView类扩展并在那里添加逻辑,但我不知道是否有更好的方法。

  • It's okay to add a custom Model class which handles the calculation?. 可以添加一个处理计算的自定义Model类吗? I've been using rails for a while and I'm used to Model === Table in database. 我已经使用rails一段时间了,我习惯于在数据库中建模=== Table。

Thank you very much! 非常感谢你!

I think Backbone View class is abstract enough. 我认为Backbone View类足够抽象。 All you have to do is to pass different options when you create new View instance. 您所要做的就是在创建新的View实例时传递不同的选项。

And I found that you place the calculating logic in View's render method. 我发现你将计算逻辑放在View的渲染方法中。 Because Backbone is a MVC-based framework, so logic should place in Model and View register event handler which is responsible for rendering layout when Model fire event which view is interested. 因为Backbone是一个基于MVC的框架,所以逻辑应该放在Model和View寄存器事件处理程序中,它负责在视图感兴趣的Model fire事件时呈现布局。

In my opinion, you could add a Model which handle calculate and redefine your view. 在我看来,您可以添加一个处理计算和重新定义视图的模型。

My simple example: 我的简单例子:

1.Define a model which is respond for logic calculating: 1.定义一个响应逻辑计算的模型:

var MathModel = Backbone.Model.extend({
    result: 0,
    initialize: function(){
        console.log("calculate target: "+this.get("selector"));
        console.log("calculate method: "+this.get("method"));
        var number = this.handlePluginData();
        this.doSomethingWithResult(number);
    },
    handlePluginData: function(){
        return $(this.get("selector")).text();
    },
    doSomethingWithResult: function(number){
        if(this.get("method")==="square"){
            this.set({result:(number*number)});
        }else{
            this.set({result:(number*number*number)});
        }

    }
});

2.Redefine the View class: 2.重新定义View类:

View will register a listener for model "result" data change event and render a initial layout according to the model you assigned. View将为模型“result”数据更改事件注册一个侦听器,并根据您指定的模型呈现初始布局。

var AbstractView = Backbone.View.extend({
        initialize: function(){
            this.listenTo(this.model,"change",this.onModelChange);
            this.number = this.model.get("result");
            this.render();
        },
        render: function(){
            this.$el.html(this.number); 
        },
        onModelChange: function(model){
            this.number = model.get("result");
            this.render();
        },
        plusOne:function(){
            this.model.doSomethingWithResult(this.model.handlePluginData());
        }
    });

3.Pass different options to model when you instantiate a new View. 3.在实例化新视图时,为模型选择不同的选项。

var view1 = new AbstractView({el:"#result1",model:new MathModel({selector:".square",method:"square"})});
var view2 = new AbstractView({el:"#result2",model:new MathModel({selector:".cubic",method:"cubic"})});

4.HTML: 4.HTML:

<div id="select-target">
    <span class="square">2</span>
    <span class="cubic">2</span>
    <button id="plus-one">+1</button>
</div>
<div id="result">
    <span id="result1"></span>
    <span id="result2"></span>
</div>

5.Plus-one button click event handler: 5.Plus-一键式点击事件处理程序:

You could observe how View re-render it's layout when model is changed. 您可以观察View在更改模型时如何重新呈现它的布局。

$("#plus-one").click(function(){
        $(".square").text(Number($(".square").text())+1);
        $(".cubic").text(Number($(".cubic").text())+1);
        view1.plusOne();
        view2.plusOne();
    });

Hope this is helpful for you. 希望这对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM