How to include observables in computed and get aro

2019-08-01 16:22发布

I'm trying to get around a resharper warning about unused variables.

Here is my current function:

self.contentDimensions = _i.ko.computed(function () {
    var fakeVarToFireComputed = self.contentSize() + self.ListLength();
    var firstEl = _i.$(itemSelector, self.viewRef()).first();
    if (firstEl.length > 0) {
        return { 
            width: firstEl.outerWidth(true), 
            height: firstEl.outerHeight(true) };
    } else {
        return self.contentDimensions();
    }
}, this, { deferEvaluation: true });

But since fakeVarToFireComputed isn't used, it throws a warning.

Here is what I've come up with:

self.contentDimensions = _i.ko.computed(function () {
    var fakeVarToFireComputed = self.contentSize() + self.ListLength();
    var firstEl = _i.$(itemSelector, self.viewRef()).first();
    if (firstEl.length > 0) {
        return { 
            width: firstEl.outerWidth(true), 
            height: firstEl.outerHeight(true),
            fake: fakeVarToFireComputed
        };
    } else {
        return self.contentDimensions();
    }
}, this, { deferEvaluation: true });

This gets rid of the warning, but is there a better way?

I tried searching for ways to include observables in a computed, but can't find a way unless you are actually using the value. I am also not really seeing a way to rewrite this as some subscribes.

1条回答
smile是对你的礼貌
2楼-- · 2019-08-01 16:33

You are right, you need to call all observable to get them register in a computed... however, you don't need to actually use their values, just execute the observables.

In your case something like this will do the trick and prevent resharper warning

self.contentDimensions = _i.ko.computed(function () {
    self.contentSize(); //Something like this will be enough
    self.ListLength(); 
    var firstEl = _i.$(itemSelector, self.viewRef()).first();
    if (firstEl.length > 0) {
        return { 
            width: firstEl.outerWidth(true), 
            height: firstEl.outerHeight(true),
            fake: fakeVarToFireComputed
        };
    } else {
        return self.contentDimensions();
    }
}, this, { deferEvaluation: true });

In a working project I have dynamic dependencies, so I pre register them and my computed looks something like this

node.isValid = ko.pureComputed(function () {
            for (var i = 0; i < this.isValidDependencies().length; i++) {
                this.isValidDependencies()[i](); //Just call every dependency
            }
            //more code, validations bla bla bla
            },node);
查看更多
登录 后发表回答