knockout / knockout

Knockout makes it easier to create rich, responsive UIs with JavaScript
http://knockoutjs.com/
Other
10.47k stars 1.51k forks source link

"with" property in "template" binding #2308

Closed miellaby closed 7 years ago

miellaby commented 7 years ago

It's a feature request.

I often replace "with" bindings by "template" bindings because I need for its afterRender feature.

But in order to emulate the "with" binding behavior (which prevents falsy data to being rendered), I have to duplicate "if" and "data" properties in these "with"-equivalent "template" bindings.

So any chance for a "with" property in the "template" binding?

brianmhunt commented 7 years ago

Is this a dupe of #2307?

How is the feature different from template: { $data: thing, if: thing }?

miellaby commented 7 years ago

@brianmhunt

What if thing is a complex Javascript expression, or has a high computation cost? Yes I'm supposed to always put computed observables in my model. But sometimes, it feels wrong doing so (a long debate I guess).

By the way, yes it's an involuntary duplicate. It looks like I've been tricked by some eventual consistency mechanism in github.

brianmhunt commented 7 years ago

@miellaby The canonical way to handle high-computation items is to cache/memoize the result.

This is generally better than modifying the API to solve this problem.

One knockout-specific option is to have a filter (in punches or tko) that memoizes e.g. thing|memoize:buster, where buster is what breaks the memoization cache i.e.

let memoized = new WeakMap()
ko.filters.memoize = function (fn, buster) {
  const key = ko.unwrap(buster)
  if (!memoized.has(key)) {
    memoized.set(key, fn())
  }
  return memoized.get(key)
}

Always open to other possibilities, too.