Accedere a un altro modello in Ember - sicuramente c'è un modo migliore dell'ajax

Sto inserendo un pulsante nell’header che aggiunge un utente a un gruppo. Questo funziona, ma fare una chiamata ajax per farlo non sembra giusto. Sembrerebbe che potrei “semplicemente” chiamare il modello Group e farlo lì, ma non riesco a trovare un esempio che lo faccia.

Questo è in un plugin…

Suppongo che ci debba essere un modo per trasformare demoGroup in un modello anziché solo un dict?

      const demoServerGroupName = siteSettings.pfaffmanager_demo_server_group;
      const groups = Site.currentProp("groups");
      const router = container.lookup("router:main");

      const demoGroup = groups.find((g) => {
        return g.name === demoServerGroupName;
      });
      const hasDemoServer = servers.find((g) => {
        return g.hostname.includes("pfaffmanagerdemo");
      });
      if (demoGroup && !hasDemoServer) {
        api.decorateWidget("header-buttons:before", (helper) => {
          const addToDemoGroup = function () {
            window.console.log("need to add to group", demoGroup);

            const groupId = demoGroup.id;
            const url = `/groups/${groupId}/join.json`;
            ajax(url, {
              type: "PUT",
              data: currentUser.username,
            })
              .then(() => {
                router.transitionTo("/pfaffmanager/servers"); //TODO: refer to the route?
              })
              .catch(popupAjaxError);
          };

          return helper.h(
            "button#newDemoServer",
            {
              className: "btn btn-text btn-primary create headerLink",
              title: I18n.t("pfaffmanager.server.create_demo_server_title"),
              onclick: addToDemoGroup,
            },
            I18n.t("pfaffmanager.server.create_demo_server_short")
          );
        });
      }
1 Mi Piace

Se l’oggetto con cui stai lavorando è un oggetto modello Group, puoi chiamare direttamente addMembers su di esso. Altrimenti, puoi usare il metodo Group.findAll.

Per l’uso, consulta il codebase.

1 Mi Piace

Hmm. Guardando più attentamente a ciò che fa groups.js, sembra che stia effettuando praticamente la stessa chiamata json che sto facendo io, e peggio ancora, il Group.findAll() che sembrerebbe necessario per poter utilizzare Group.addMembers aggiunge una chiamata ajax extra che sto attualmente evitando. Forse il mio codice non è così male come pensavo!

Grazie!

1 Mi Piace