Maintaining a model when a bound property changes

When it comes to persisting a model immediately, especially when one of its attributes is bound to a template input, the debate arises - should this functionality belong to the model or the controller?

In an attempt to address this dilemma, I devised a solution involving an observer:

# Models
App.Foo = DS.Model.extend
  bars: DS.hasMany('bars')

App.Bar = DS.Model.extend
  quantity: DS.attr('number')

# Template
{{#each bar in bars}}
  {{input value=bar.quantity}}
{{/each}}

# Controller
persistQuantity: ( ->
  @get('bars').forEach (bar) -> bar.save() if bar.get('isDirty')
).observes('[email protected]')

However, this implementation seems to trigger multiple save requests (in my case, 3) for the same model.

Another approach I experimented with was placing the observer directly on the model, but it resulted in an infinite loop:

# App.Bar Model
  persistQuantity: ( ->
    @save()
  ).observes('quantity')

Efforts to resolve this issue by utilizing Ember.run.once were not successful, revealing gaps in my understanding of Ember's run loop mechanisms.

Answer №1

When deciding where to place the responsibility for saving a model, consider whether you want the model to save every time it changes or only when it transitions between specific views. If you prefer the model to always save regardless of its location, handle it within the model itself. On the other hand, if you want to control when the model is saved from a specific view, manage it in the controller.

To address the issue of multiple calls, utilizing debouncing can be an effective solution. By monitoring a specific item and triggering automatic saving upon any changes, you can prevent unnecessary duplicate calls. While observing isDirty and reacting accordingly is another approach, the former method tends to be more favorable due to its clarity. Below are examples demonstrating both techniques, which can be customized according to your requirements:

Implement auto-saving functionality in the model when it becomes dirty:

App.Bar = DS.Model.extend
  quantity: DS.attr('number'),
  watchDirty: function(){
    if(this.get('isDirty')){
      this.save();
    }
  }.observes('isDirty')

Example:

Utilize debounce to queue saving when an item becomes dirty (or multiple items):

App.Bar = DS.Model.extend({
    quantity: DS.attr(),  
    watchQuantity: function(){
      if(this.get('isDirty')){
        Em.run.debounce(this, this.save, 500); 
      }
    }.observes('quantity')
});

Example:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for displaying an object's key/value pairs on a webpage

I'm attempting to use jQuery's .each() function to write the key/value pairs from an object onto the page. However, I am only able to get it to display the last key/value pair. If you want to check out a code example and demo, here is the link: ...

What are the steps to restrict the scope of a <style> declaration in HTML?

Currently, I am in the process of creating a user interface for a webmail. Whenever I receive an email, I extract its content and place it within a <div> element for display purposes. However, one challenge that I am facing is that each email contain ...

Apologies, but it seems that the function Buffer.write(string, encoding, offset[, length]) is no longer supported

Currently, I am diving into the world of ExpressJS and Node.js. However, I have hit a roadblock when a user enters data in a form and clicks submit, resulting in an error. Despite my extensive research on this issue, I have been unable to find a satisfacto ...

Implement a validation function in the "jQuery validation library."

Hello, I am currently using the jQuery validation plugin to validate my form. I am trying to add an additional rule to the validation, but I am struggling to get it to work. The input value should be less than or equal to the previous element's value. ...

Executing Javascript and C# functions through a single click

I need to call a method in Javascript and a method in C# when a button is clicked. First, I want to call the C# method called 'Find_Direction' on click, which takes two inputs. Then, I want to call the Javascript method named calcRoute. I attem ...

Methods for removing and iterating through images?

I successfully programmed the image to move from right to left, but now I want to add a function where the image is deleted once it reaches x: 50 and redrawn on the left. I attempted to use control statements like "if," but unfortunately it did not work a ...

Having trouble with dragging a file from one box to another in HTML5. The functionality is not working

Encountering an issue where the image does not display in the left box after dropping it. Here is the sequence of events: Before dragging the image: https://i.sstatic.net/C6JSM.png After dragging the image, it fails to display: https://i.sstatic.net/7Du0 ...

Developing a quiz using jQuery to load and save quiz options

code: http://jsfiddle.net/HB8h9/7/ <div id="tab-2" class="tab-content"> <label for="tfq" title="Enter a true or false question"> Add a Multiple Choice Question </label> <br /> <textarea name ...

Learning to retrieve specific properties from an event target in JavaScript

Here is the code snippet I am working with: <h1 msgId = "someId"> Some text </h1> And in my code.js file, I have the following function: document.addEventListener('click', function(e) { target = e.target; }, false); I am tryin ...

Utilizing ReactJS for Web Development with Enhanced Data Insights from Google

Utilizing Google Analytics and various tools, I've encountered an issue with the development of ReactJS. My goal was to collect analytics data from my website by using react-helmet to dynamically change the title and the HTML lang parameter based on t ...

Issues with Autofocus while Searching and Selecting from Dropdown menu

Here is the JavaScript code I am using: <script type="text/javascript"> function handleSelectionChange(selectElement, nextField) { nextField.focus(); } function handleKeyPress(event, currentField, nextField) { i ...

The defined function in Node.js did not work properly with the callback

This code snippet demonstrates how to use the findOne() method with Node.js and MongoDB. var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/blog', function(err, db) { if(err) throw er ...

Developing a custom function that analyzes two distinct arrays and sends any corresponding pairs to a component

I'm in the process of developing a component that utilizes two arrays. These arrays are then mapped, and the matching pairs are sent down as props to a child component. The goal is to create a list component that retrieves the arrays from the backend ...

Linking states using AngularJS and jQuery

Imagine I have a scenario with two different states: .state('page1', { url: '/page1', templateUrl: 'pages/templates/page1.html', controller: 'page1' }) .state('page2', { url: '/page2& ...

The function angular.element() is unable to locate the specified DOM element

My dilemma lies in the fact that I have a dynamic table of users extracted from a Firebase database: <table id="users"> <thead> ... </thead> <tbody> <tr ng-repeat="user in users"> <td da ...

Having trouble terminating the session with the authentication provider SSO on Node JS

I'm struggling with ending the session properly when a user makes a request to my /logout endpoint. I want to clear the session and require the user to log in again via SSO. Currently, after an initial login, I remain logged in without needing to re-e ...

Manage image placement using CSS object-position

I have the following code snippet: img{ width: 100%; height: 1000px; object-fit: cover; object-position: left; } <!DOCTYPE html> <html lang="en"> <head> <meta charset ...

Retrieving Parts of a URL in AngularJS

Is there a way to extract all parts of a URL after "/"? For example: http://myadress.com/#/example/url/here/param1 Result: ['example', 'url', 'here']. Currently, $routeParams only returns an object with route parameters lik ...

I am perplexed as to why none of the scripts I attempt to use are effective in changing the active item

I am struggling to change the active item in my bootstrap navbar. I came across a similar question on this topic: Bootstrap navbar Active State not working Despite trying all of the suggested solutions, none seem to work for me and I can't figure out ...

Implementing JavaScript logic to proceed to the following array within a 3D array once a specific condition is met

I'm currently tackling a challenge that requires me to obtain a specific number using a given 3D array. This array consists of 2D arrays, each containing the same number repeated x times. The parent array is sorted from largest to smallest. Here&apos ...