2

我对 Backbone.js 很陌生,但我喜欢 jQuery。然而,我喜欢 Backbone 将代码组织成模型、视图和集合的方式,但我仍然无法理解在编写 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/

4

1 回答 1

4

免责声明:与 Backbone 中的任何解决方案一样,有多种方法可以处理给定问题,以下答案可能完全是矫枉过正,应谨慎使用。

定义你的模型

它们将代表您的数据以及应如何处理它。在这里,我将定义一个 Question 模型(空的,但你永远不知道),一个 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);
    }
});

定义你的观点

它们将在 DOM 中显示模型的状态,并处理与用户的交互。让我们有一个处理输入的 SearchView 和一个显示当前建议的 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/

当然,您可以通过让单个视图处理所有交互来大大简化此操作,但乐趣在哪里呢?

于 2012-08-15T11:43:55.140 回答