【问题标题】:require.js and backbone.js getting Uncaught TypeErrorrequire.js 和backbone.js 得到Uncaught TypeError
【发布时间】:2014-02-18 21:33:56
【问题描述】:

我正在尝试使用backbone.js 编写一个简单的应用程序,最终将模型保存在indexedDB 中并显示它们。我松散地基于骨干示例中的待办事项应用程序。 当我不使用 require.js 时它工作正常。

当我尝试使用 require 时,虽然我得到一个 Uncaught TypeError: Object # has no method 'on' 错误,这似乎指向我在我的一个视图中添加一些事件监听器的点。

我的文件是这样排列的:文件夹“js”中有文件夹“app”、“lib”和“tpl”以及main.js。在应用程序中有一个包含 taskItemView 和 taskListView 的文件夹“控制器”,以及一个包含我的 taskModel.js 和 database.js 的文件夹“模型”。在“lib”文件夹中是我的外部库、主干、下划线、jquery、json2、require、text、indexedDB 主干-indexeddb.js 的适配器和仅支持 websql 的浏览器的 shim,IndexedDBShim.js。

这是我的 main.js,我正在尝试配置 require。

require.config({
baseUrl: "js/lib",

paths: {
    app: '../app',
    tpl: '../tpl'
},

shim: {
    'backbone': {
        deps: ['underscore', 'jquery'],
        exports: 'Backbone'
    },
    'underscore': {
        exports: '_'
    },
    'backbone-indexeddb': {
        deps:['backbone']
    },
    'IndexedDBShim': {
        deps:['backbone']
    }
}
});


require(
    ['backbone', 'app/router'], function ( Backbone, Router) {
        var router = new Router();
        Backbone.history.start();
    }
);

我的 taskListView 中的第 22 行出现错误,这里。

define(function (require) {
"use strict";
var $           = require('jquery'),
    Backbone    = require('backbone'),
    _           = require('underscore'),
    //Template    = require('text!tpl/taskListView.html'),
    taskList    = require('app/model/taskModel');

//the collection for our tasks
//var Tasks = new TaskList;

//this will handle all the user inputs and the output for the gui.
 return Backbone.View.extend({
    el: $("#taskApp"),
    //on enter keypress fires createOnEnter
    events: {
        "keypress #taskInput": "createOnEnter",
    },
    //initializes the app
    initialize: function () {
        //listeners
        this.listenTo(taskList, 'add', this.addOne); //this is where the error comes from.
        this.listenTo(taskList, 'all', this.render);
        //get the template
        //var template = _.template(Template);
        template: _.template($('#taskListView').html()),
        //apply template
        this.$el.html(template);
        //get text input field
        this.input = this.$("#taskInput");

        this.main = $('#main');
        //fetch old entries
        taskList.fetch();
    },
    //renders the main section
    render: function () {
        this.main.show();
    },
    //appends an item to the list
    addOne: function (taskModel) {
        var view = new taskItemView({
            model: taskModel
        });
        this.$("#taskList").append(view.render().el);
    },
    //creates a new item from the text input field
    createOnEnter: function (e) {
        //check for valid input (enter)
        if (e.keyCode != 13) return;
        //check if input is empty
        if (!this.input.val()) return;
        //get data
        var inputData = this.input.val();
        //creates and adds new item to collection
        taskList.create({
            title: inputData
        });
        //clear input field
        this.input.val('');
    },
});
});

只是为了完成,这是我的 taskItemView:

define(function (require){
"use strict";
var $           = require('lib/jquery'),
    _           = require('lib/underscore'),
    Backbone    = require('lib/backbone');
    //Template    = require('lib/text!tpl/taskItemTemplate.html');

//manage task items and binding
return Backbone.View.extend({
    tagName: "li",
    classname: "topcoat-list__item",

    //template used for task Items       
    template: _.template($('#taskItemView').html()),
    //template: _.template(Template),

    //initialize, create listener for changes in model
    initialize: function () {
        this.listenTo(this.model, 'change', this.render);
    },

    //use template to display task items
    render: function () {
        //fetch JSON representation of model
        var modelJSONrepresentation = this.model.toJSON();
        //inject into template
        var templating = this.template(modelJSONrepresentation);
        //apply template
        this.$el.html(templating);
        return this;
    }
});
});

我的模特:

define(function (require) {
"use strict";

    var $               = require('jquery'),
        Backbone        = require('backbone'),
        //taskDatabase    = require('app/model/database'),

        //manage task items
        task = Backbone.Model.extend({
            //bind indexedDB
            //database: taskDatabase,
            //storeName: "tasks",
            defaults: function () {
                return {
                    title: "test"
                };
            }
        }),
        //manage list of tasks
        taskList = Backbone.Collection.extend({
            //bind model
            model: task,
            //bind indexedDB
            //database: taskDatabase,
            //storeName: "tasks"
        });
    return {
        task: task,
        taskList: taskList
    };
});

数据库管理员,

define(function (require){
"use strict";


//create indexedDB 
var taskDatabase = {
    id: "taskDataBase4",
    description: "The Database used in the TaskList App",
    migrations: [{
        version: 1,
        migrate: function (transaction, next) {
            var store = undefined;
            //create store if it doesn't exist already
            if (!transaction.db.objectStoreNames.contains("tasks")) {
                store = transaction.db.createObjectStore("tasks")
            }
            store = transaction.objectStore("tasks");

            next();
        }
    }]
}
});

还有我的路由器。我没有在 non-require.js 应用程序中使用一个,但我必须在这里使用一个。

define(function (require){

"use strict";

var $               = require('jquery'),
    Backbone        = require('backbone'),
    TaskListView    = require('app/controller/taskListView');

    taskListView = new TaskListView();

    return Backbone.Router.extend({
        routes: {
            "": "home"
        },

        home: function() {
            console.log("derp");
            taskListView.delegateEvents();
        }
    });
});

我很茫然,永远感激不尽。

编辑:完整的错误堆栈:

    Uncaught TypeError: Object #<Object> has no method 'on' backbone.js:226
Events.(anonymous function) backbone.js:226
Backbone.View.extend.initialize taskListView.js:22
Backbone.View backbone.js:1002
child backbone.js:1567
(anonymous function) router.js:9
context.execCb require.js:1650
Module.check require.js:866
(anonymous function) require.js:1113
(anonymous function) require.js:132
(anonymous function) require.js:1156
each require.js:57
Module.emit require.js:1155
Module.check require.js:917
(anonymous function) require.js:1113
(anonymous function) require.js:132
(anonymous function) require.js:1156
each require.js:57
Module.emit require.js:1155
Module.check require.js:917
(anonymous function) require.js:1113
(anonymous function) require.js:132
(anonymous function) require.js:1156
each require.js:57
Module.emit require.js:1155
Module.check require.js:917
Module.enable require.js:1143
Module.init require.js:774
callGetModule require.js:1170
context.completeLoad require.js:1544
context.onScriptLoad

【问题讨论】:

  • 你称为“我的模型”的文件是taskList = require('app/model/taskModel');导入的文件吗?

标签: javascript jquery backbone.js requirejs


【解决方案1】:

listenTo 方法需要一个模型实例作为第一个参数,而不是传递包含模型定义的变量 taskList。请创建模型实例,然后将其传递给 listenTo 方法。

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 2012-08-30
    • 2014-05-28
    • 1970-01-01
    相关资源
    最近更新 更多