使用Backbone.js创建一个模态

Creating a Modal using Backbone.js

本文关键字:一个 模态 Backbone js 创建 使用      更新时间:2023-09-26

我是新的骨干,虽然我做了一些研究,我找不到一个解决方案,将为我工作,在创建一个模态方面。我想创建一个基本的模态类,然后重用/扩展它,并应用不同的模板,在我的其他视图/类。

这是我的Modal基类:

define([
  // Application.
  'app',
  'backbone',
  'plugins/jquery-ui.custom',
  'moment'
], function(App, Backbone) {
  // Create a new module.
  var Modal = App.module();
  Modal.View = Backbone.View.extend({
      className: 'ui-modal',
  render: function () {
      console.log('this.$el',this.$el,'this.template',this.template);
        this.$el.html(this.template());
        this.$el.delegate('.close', 'click', this.closeModal);
        this.error = this.$el.find('.error');
        return this;
      },
  closeModal: function (ev) {
        if (ev) ev.preventDefault();
        this.$el.unbind();
        this.$el.empty();
        this.$el.remove();
      },
  initialize: function () {
      console.log('initialize modal view', 'this.$el', this.$el);
        _.bindAll(this, 'render', 'closeModal');
        return Backbone.View.prototype.initialize.call(this);
    }
  });

我试图在这里扩展/利用Modal类:

ProductDetails.Views.testView = Modal.View.extend({
    template: 'modals/ProductDetails/testView',
    render: function() {
      Modal.View.prototype.render.call(this);
      this.delegateEvents();
      return this;
    },
    initialize: function() {
      console.log('initialize testView','this.$el',this.$el);
      return Modal.View.prototype.initialize.call(this);
    }
  });

我试图触发Modal在这里:

ProductDetails.Views.Description = Backbone.View.extend({
    template: 'partials/product/description',
    initialize: function(){
      _.bindAll(this, 'serialize', 'warn', 'error', 'updateModel', 'testModalView');
      //instantiate the test modal
      this.testView = new ProductDetails.Views.testView();
      this.testView.$el = this.$el;
    },
    serialize: function(){
     //some stuff
    },
    events: {
      'click .testModalView_link': 'testModalView'
       //some other stuff
    },
    warn: function() {
      //some stuff
    },
    error: function(error){
      //some stuff
    },
    updateModel: function(e){
      //some stuff
    },
    testModalView: function(ev) {
      try {
        ev.preventDefault();
        $('.ui-modal').append(this.testView.render())
      } catch(e) {
        console.log(e.message,e);
      }
    }
  });

我已经检查过了,但是我可能在试图简化包含在这个问题中的代码时犯了一个错误。当我通过点击链接(类. testmodalview_link)测试我的模态时,我得到了错误:"TypeError: this。$el is undefined",它指向模态基类,指向这一行:

this.$el.html(this.template());

谁能帮我做这个工作,或者至少理解我做错了什么?

谢谢。

谢谢你的帮助。我将继续讨论这个问题,我花了很多时间调试它,甚至研究替代实现;最后,我认为问题是我们加载和编译模板的方式,或者是我们正在使用的库/插件的版本。我还注意到,当DOM没有完全加载或元素在呈现之前被访问时,也会出现类似的问题;同样,也可能是绑定和回调没有正确处理作用域。如果我重新审视这个问题并找到可靠的答案,我一定会提供一个更新。