打开你的jQuery代码到Backbone.js的结构(Turning your jQuery co

2019-09-21 05:32发布

我很一个小白到Backbone.js的,但我喜欢jQuery的。 但是我爱骨干是如何组织的代码转换成模型,视图和收藏,但我还是不能让我的周围写JS代码,当我将如何使用它的头。

例如采取这种简单的代码,我在jQuery的写了一个附加的建议箱时,在输入框中输入一个用户类型:

// 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>");
        }
    }
});

在构建这样使用Backbone.js的结构的微型功能有什么建议? 我不是说写整个代码,只是一个粗略的指南或解释将不胜感激。

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

Answer 1:

免责声明 :在骨干网的任何解决方案,有多种方法来处理一个给定的问题,下面的答案很可能是完全矫枉过正,应以应有的谨慎服用。

定义你的模型

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

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

定义你的看法

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

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

把模型和视图一起

实例,结合事件和运行的东西

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

和小提琴一起玩http://jsfiddle.net/nikoshr/QSE95/

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



文章来源: Turning your jQuery code into a Backbone.js structure