How to include observables in computed and get around resharper warning?

廉价感情. 提交于 2019-12-13 19:21:04

问题


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:


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);


来源:https://stackoverflow.com/questions/38126891/how-to-include-observables-in-computed-and-get-around-resharper-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!