Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feedback about multiple-pushes #11

Open
lunks opened this issue May 27, 2024 · 1 comment
Open

Feedback about multiple-pushes #11

lunks opened this issue May 27, 2024 · 1 comment

Comments

@lunks
Copy link

lunks commented May 27, 2024

It could be a bit more didactic if in the recap you added diffs from the initial code to the final one.

Another question, why do we have to do js \\ %JS{} instead of %JS{} as the first argument on add_points?

@lubien
Copy link
Member

lubien commented May 27, 2024

Another question, why do we have to do js \\ %JS{} instead of %JS{} as the first argument on add_points?

The reason for that is that we could use both add_points(type, number) (js defaults to %JS{}) or chain like this: add_points(type, number) |> add_points(type, number)

Since add_points/3 will return a %JS{}, the second add_points call will receive the previous one and use it so its the same as:

js = add_points(type, number)
add_points(js, type, number)

Why do we need to pass the %JS{} around?

Every time you use JS.push or any other JS Commands function what you are actually creating is a data structure called %JS{}. When empty it looks like this: %Phoenix.LiveView.JS{ops: []}. It contains the list of operations that will be performed.

If we ignore the previous %JS{} we will only do the second operation which would not do what you wanted. Wanna check this bug? Edit your function to:

  defp add_points(js \\ %JS{}, team, amount) do
    # BUG: always ignore the `js` and use a new one below!
    JS.push(%JS{}, "add_points", value: %{team: team, amount: amount})
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants