【问题标题】:Manually create a computed property手动创建计算属性
【发布时间】:2014-04-30 14:39:36
【问题描述】:

这就是问题所在。我目前正在创建一个 mixin 来处理表单验证。问题是我想在 init 方法中创建一个计算属性isFormValid,它是'is<fieldName>Valid' 其他属性的'computed.and' 属性。

我可以创建它,但它永远不会更新。我想我需要添加观察者,但也许有人会有更好的解决方案?

编辑
这里有一些说明。

我的控制器获得了该属性:

App.FormViewController = Ember.Controller.extend(App.ValidatorMixin, {
    validations: {
        field1: {
            errLvl: App.Validation.ErrLvl.ERROR,
            type: App.Validation.Type.TEXT,
            pattern: /^\d{6}$/,
            message: 'Error message'
        },
        field2: {
            //somecode
        }
    }
});

mixin 定义如下:

App.ValidatorMixin = Ember.Mixin.create({
    init: function() {
        this._super();

        var self = this;
        Ember.keys(this.validations).forEach(function(prop) {
            self.set('is' + prop.capitalize() + 'Valid', false); //Is changed when the field is valid
        });
    }
});

isFormValid 属性应该是所有这些 is<fieldName>Valid 中的一个 Ember.computed.and

EDIT2
表单上的每个输入都由输入助手和这个 mixin 定义:

App.Mixin.ValidatableInput = Ember.Mixin.create({
    focusOut: function() {
        this.validate();
    },
    //Do the validation
    validate: function() {
        //I'm currently moving that part to the controller because it's part
        //of the logic but it was easier for a start to write it here

        //We update the is<fieldName>Valid property
        this.get('parentView.controller').set('is' + this.get('name').capitalize() + 'Valid', !hasError);

        //Then some DOM manipulation to attach the error message
    }
});

最后我的看法是这样的

{{view App.CustomTextField name="field1" value=field1}}
{{view view.buttonCreate disabled=isFormInvalid}}

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    init 方法中,您可以使用defineProperty 设置计算属性。

    Ember.defineProperty(myObject, 'myProperty', Ember.computed(function computed() {
    
        return 'myValue';
    
    }).property('myObserver'));
    

    【讨论】:

    • 我不能这样做,因为myObserver 是一个动态生成值的数组。我也可以this.set('isFormValid', Ember.computed(...).property()) 第一次设置它,但在更新依赖键时不更新。
    • 那么myObserver.length 会在每次更新数组时触发吗?你也有myObserver.@each,它可以做同样的事情。
    • 不幸的是它不起作用,因为我不更新数组而是数组引用的属性。
    【解决方案2】:

    这对你有用吗? (扩展@Wildhoney,我无法评论)。如果您有多个属性,您可以指定多个属性:

    Ember.defineProperty(myObject, 'myProperty', Ember.computed(function computed() {
    
        return 'myValue';
    
    }).property('myObserver.@each.myObservedProperty'));
    

    我在 Ember 中使用 jQuery Validate 有点运气,方法是触发表单视图的 didInsertElement 上的 .validate() 调用和规则,然后在您关注每个 Ember.TextField 时执行 .valid() 检查.我强烈推荐它用于表单验证。

    【讨论】:

      猜你喜欢
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 2019-03-31
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多