把你的jQuery code到Backbone.js的结构 [英] Turning your jQuery code into a Backbone.js structure

查看:108
本文介绍了把你的jQuery code到Backbone.js的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当小白到Backbone.js的,但我喜欢jQuery的。不过,我爱骨干是如何组织的code为模型,视图和收藏,但我还是不能让我的头周围写JS code,当我将如何使用它。

例如采取这种简单的code我jQuery中写道,追加一个建议箱,当用户在输入框:

  //这是模型
VAR问题= [
    {问题:你叫什么名字},
    {问题:你多大了?},
    {问题:什么是你母亲的名字},
    {问题:在哪里工作/或学习}
];//搜索数据功能
功能searchData(DATAS,期限){
    返回_.filter(DATAS,函数(OBJ){
        返回〜obj.question.toLowerCase()的indexOf(项)。
    });
}//活动
$(#suggestinput)。关于({
    KEYUP:功能(){
        VAR的结果= searchData(问题,THIS.VALUE);
        $(#建议)
            .addClass(活动)
            的.html(_。减少(结果,功能(最后,Q){
                返回最后+&所述; P>中+ q.question +&下; / P>中;
             },));
    },
    模糊:功能(){
        $(#建议)removeClass移除(激活)。
        $(#建议)HTML()。
    },
    重点:函数(){
        如果($(本).VAL()===){
            $(#建议)addClass(激活)。
            $(#建议)HTML(< P>开始键入问题和LT; / P>中);
        }
    }
});

在构建这样使用Backbone.js的结构的微型功能有什么建议?我不是说写全code,只是一个粗略的指引或解释是多少AP preciated。

还有关于这个的jsfiddle code的工作示例: http://jsfiddle.net/X8geT / 1 /


解决方案

免责声明的:作为骨干任何解决方案,有多种方法来处理一个给定的问题,下面的答案很可能是完全矫枉过正并应采取一切适当的谨慎。

定义模型

他们将重新present您的数据,它应该如何处理。在这里,我将定义一个问题模型(空的,但你永远不知道),一个问题集(其中过滤任期的定义),以及搜索状态控制器负责存储本期和匹配问题:

  VAR问题= Backbone.Model.extend();VAR问题= Backbone.Collection.extend({
    型号:问题,
    匹配:功能(项){
        如果(长期===)
            返回[];        长期= term.toLowerCase();
        返回this.filter(函数(模型){
            返回model.get('问题')与toLowerCase()的indexOf(项)== - !1
        });
    }
});VAR QuestionController = Backbone.Model.extend({
    默认值:{
        长期:
    },
    初始化:功能(选){
        this.questions = opts.questions; //众所周知的问题
        this.matches =新问题(); //过滤问题        //当长期变化,更新匹配
        this.on('的变化:术语,功能(模型,期限){
            this.matches.reset(this.questions.matches(项));
        }, 这个);
    }
});

定义你的看法

它们将显示在DOM模型的状态,并且将处理与用户的互动。让我们搜索查看将处理输入和SuggestionsView将显示当前建议:

  VAR搜索查看= Backbone.View.extend({
    事件:{
        KEYUP':功能(E){
            this.model.set('术语',这$ el.val());
        },
        '专注':功能(E){
            this.trigger('开始');
        },
        模糊处理:功能(E){
            this.trigger('一站式');
        }
    }
});VAR SuggestionsView = Backbone.View.extend({
    初始化:功能(){
        _.bindAll(这一点,'激活','取消','渲染');
        this.listenTo(this.model.matches,复位,this.render);
    },
    激活:功能(){
        这$ el.addClass(激活)。
        this.render();
    },
    关闭:函数(){
        这$ el.removeClass(激活)。
        这$ el.html();
    },
    渲染:功能(){
        VAR HTML ='';        如果(this.model.get(期限)===){
            HTML =< P>开始键入问题和LT; / P>中;
        }其他{
            如果(this.model.matches.length === 0){
                HTML =< P>不匹配< / P>中;
            }其他{
                this.model.matches.each(函数(模型){
                    HTML + ='< P>'+ model.get('问题')+'< / P>';
                });
            }
        }
        这$ el.html(HTML);
    }
});

把模型和视图一起

实例化,事件绑定和运行的东西。

  VAR问题=新课题([
    {问题:你叫什么名字},
    {问题:你多大了?},
    {问题:什么是你母亲的名字},
    {问题:在哪里工作/或学习}
]);
VAR控制器=新QuestionController({
    问题:问题
});VAR vSearch =新的搜索查看({
    EL:#suggestinput',
    型号:控制器
});
VAR vSuggestions =新SuggestionsView({
    EL:#suggestions',
    型号:控制器
});vSuggestions.listenTo(vSearch,开始,vSuggestions.activate);
vSuggestions.listenTo(vSearch,停,vSuggestions.deactivate);

和一拨弄 http://jsfiddle.net/nikoshr/QSE95/ <玩/ p>

当然,你可以大大有处理所有交互的单一视图简化了这一点,但会在哪里好玩?

I'm quite a noob to Backbone.js, but I love jQuery. However I love how Backbone organizes the code into models, views and collections but I still can't get my head around how I would use it when writing JS code.

For example take this simple code I wrote in jQuery that appends a suggestions box when a user types in an input box:

// this is the model
var questions = [
    {question: "what is your name"},
    {question: "How old are you"},
    {question: "what is your mothers name"},
    {question: "where do work/or study"}
];

// search data function
function searchData(datas,term){
    return _.filter(datas, function(obj) {
        return ~obj.question.toLowerCase().indexOf(term);
    });
}

// Events
$("#suggestinput").on({
    keyup: function(){
        var results = searchData(questions, this.value);
        $("#suggestions")
            .addClass("active")
            .html(_.reduce(results, function(last, q){
                return last + "<p>" + q.question + "</p>";
             }, ""));
    },
    blur: function () {
        $("#suggestions").removeClass('active');
        $("#suggestions").html(" ");
    },
    focus: function () {
        if ( $(this).val() === "" ) {
            $("#suggestions").addClass('active');
            $("#suggestions").html("<p> start typing a question </p>");
        }
    }
});

Any advice on constructing a mini feature like this using the Backbone.js structure? I'm not saying to write the whole code, just a rough guideline or an explanation would be much appreciated.

There's also a working example of this code on JSFiddle: http://jsfiddle.net/X8geT/1/

解决方案

Disclaimer: as any solution in Backbone, there are multiple ways to deal with a given problem, the following answer is probably completely overkill and should be taken with all due circumspection.

Define your models

They will represent your data and how it should be handled. Here I will define a Question model (empty, but you never know), a Questions collection (where filtering for a term is defined), and a search state controller responsible for storing the current term and the matching questions:

var Question = Backbone.Model.extend();

var Questions = Backbone.Collection.extend({
    model: Question,
    matches: function (term) {
        if (term==="")
            return [];

        term = term.toLowerCase();
        return this.filter(function(model) {
            return model.get('question').toLowerCase().indexOf(term)!==-1
        });
    }
});

var QuestionController = Backbone.Model.extend({
    defaults: {
        term: ""
    },
    initialize: function(opts) {
        this.questions = opts.questions; //known questions
        this.matches = new Questions();  //filtered questions

        //when the term changes, update the matches
        this.on('change:term', function (model, term) {
            this.matches.reset(this.questions.matches(term));
        }, this);
    }
});

Define your views

They will display the state of the models in the DOM and will handle interactions with the user. Let's have a SearchView that will handle the input and a SuggestionsView that will display the current suggestions:

var SearchView = Backbone.View.extend({
    events: {
        'keyup ': function (e) {
            this.model.set('term', this.$el.val());
        },
        'focus ': function (e) {
            this.trigger('start');
        },
        'blur ': function (e) {
            this.trigger('stop');
        }
    }
});

var SuggestionsView = Backbone.View.extend({
    initialize: function () {
        _.bindAll(this, 'activate', 'deactivate', 'render');
        this.listenTo(this.model.matches, 'reset', this.render);
    },
    activate: function () {
        this.$el.addClass('active');
        this.render();
    },
    deactivate: function () {
        this.$el.removeClass('active');
        this.$el.html(" ");
    },
    render: function () {
        var html = '';

        if (this.model.get("term") === "") {
            html = "<p> start typing a question </p>";
        } else {
            if (this.model.matches.length === 0) {
                html = "<p> No match </p>";
            } else {
                this.model.matches.each(function(model) {
                    html += '<p>'+model.get('question')+'</p>';            
                });
            }
        }        
        this.$el.html(html);
    }
});

Bring models and views together

Instantiate, bind events and run things

var questions = new Questions([
    {question: "what is your name"},
    {question: "How old are you"},
    {question: "what is your mothers name"},
    {question: "where do work/or study"}
]);
var controller = new QuestionController({
    questions: questions
});

var vSearch = new SearchView({
    el: '#suggestinput',
    model: controller
});
var vSuggestions=new SuggestionsView({
    el: '#suggestions',
    model: controller
});

vSuggestions.listenTo(vSearch, 'start', vSuggestions.activate);
vSuggestions.listenTo(vSearch, 'stop', vSuggestions.deactivate);

And a Fiddle to play with http://jsfiddle.net/nikoshr/QSE95/

Of course, you could greatly simplify this by having a single view handling all interactions, but where would be the fun?

这篇关于把你的jQuery code到Backbone.js的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆