knockoutjs:为什么发送的是一个空对象?

发布于 2024-12-24 15:59:29 字数 3654 浏览 0 评论 0原文

我正在尝试使用knockoutjs 编写rails3 crud 视图。不知何故,我得到的行为与教程完全不同,如果您能给我一些提示,我将不胜感激...

我的代码更多的是 加载和保存数据教程。我从服务器加载数据,什么都不做,保存,控制器获取额外的“空”对象,该对象以某种方式被持久化。然而,对现有数据的更改永远不会发生,也不会被删除。

我可以显示代码:

%ul#folders{'data-bind' => 'foreach: folders, visible: folders().length > 0'}
  %li
    %span{'data-bind' => 'text: id'}
    %span{'data-bind' => 'text: name'}
    %span{'data-bind' => 'text: description, visible: description'}
    %a{'data-bind' => 'click: $parent.removeFolder'}Excluir

%button{'data-bind' => 'click: save'}Salvar

%form{'data-bind' => 'submit: addFolder'}
  Add folder:
  %input{'data-bind' => 'value: newFolderName', 'placeholder'=>"Nome"}
  %button{type: "submit"}Adicionar

=content_for :script do
  :javascript

    function Folder(data) {
      data = data || {id: 0, name: "", description: ""};
      this.id = data.id;
      this.name = ko.observable(data.name);
      this.description = ko.observable(data.description);
    }

    function FolderListViewModel() {
      var self = this;
      self.folders = ko.observableArray([]);
      self.newFolderName = ko.observable();

      $.getJSON("/folders", function(allData) {
        var mappedFolders = $.map(allData, function(item) {
          return new Folder(item);
        });
        self.folders(mappedFolders);
      });

      self.addFolder = function() {
        self.folders.push(new Folder({name: self.newFolderName()}));
        self.newFolderName("");
      };

      self.removeFolder = function(folder) {
        self.folders.remove(folder);
      };

      self.save = function() {
        console.log(self.folders());
        $.ajax("/folders", {
          data: ko.toJSON({folders: self.folders}),
          type: "post",
          contentType: "application/json",
          success: function(result) {
            return console.log(result);
          }
        });
      };
    }

    $(function(){
      ko.applyBindings(new FolderListViewModel());
    });

保存(无论是否有更改都是独立的)总是会产生类似的请求:

Started POST "/folders" for 127.0.0.1 at 2012-01-04 22:57:40 +0100
  Processing by FoldersController#create as */*
  Parameters: {"folders"=>[{"id"=>2, "name"=>"dim sum", "description"=>"ist warm!"}, {"id"=>3, "name"=>"Sushi", "description"=>"roh und kalt"}, {"id"=>1, "name"=>"Spagetti", "description"=>"Carbonara"}, {"id"=>10, "name"=>"Wiener", "description"=>"vom Kalb"}, {"id"=>11, "name"=>"Feijão", "description"=>""}], 
"folder"=>{}} <== LOOK HERE
  Folder Load (0.3ms)  SELECT "folders".* FROM "folders" ORDER BY "folders"."row_order"
   (0.1ms)  BEGIN
  Folder Load (0.2ms)  SELECT id, row_order FROM "folders" ORDER BY "folders"."row_order" DESC LIMIT 1
  Folder Load (0.2ms)  SELECT id, row_order FROM "folders" WHERE "folders"."row_order" = 8388592 LIMIT 1
  SQL (0.4ms)  INSERT INTO "folders" ("created_at", "description", "name", "row_order", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", Wed, 04 Jan 2012 21:57:40 UTC +00:00], ["description", nil], ["name", nil], ["row_order", 8388592], ["updated_at", Wed, 04 Jan 2012 21:57:40 UTC +00:00]]
   (0.5ms)  COMMIT
Redirected to http://0.0.0.0:3000/folders/21
Completed 302 Found in 54ms

删除的对象也只会从数组中删除,我想知道rails应该如何弄清楚,它应该将它们从对象存储中删除。 ..一切都只是一个帖子...这对我来说看起来都是错误的。 我的错误是什么?

两个奖励问题: 我不喜欢用这些构造函数来填充我的全局 js 命名空间,但如果我尝试将它们隐藏在匿名函数中,似乎 ko 再也找不到它们了。这可以补救吗?

我怎样才能全局告诉 Rails,停止将我重定向到 json 请求上的 html 操作(无论如何,这有多愚蠢),而只是向我发送一条 ok 消息或错误消息?

I am trying to write rails3 crud views using knockoutjs. Somehow I am getting a behavior quite different from the tutorials and would be thankful, if you could give me some hints...

My code is more a less a replication of the loading and saving data tutorial. I load the data from the server, do nothing at all, save and the controller gets and additional, 'empty' object, which somehow is persisted. However changes to existing data never is, neither deletes.

May I show the code:

%ul#folders{'data-bind' => 'foreach: folders, visible: folders().length > 0'}
  %li
    %span{'data-bind' => 'text: id'}
    %span{'data-bind' => 'text: name'}
    %span{'data-bind' => 'text: description, visible: description'}
    %a{'data-bind' => 'click: $parent.removeFolder'}Excluir

%button{'data-bind' => 'click: save'}Salvar

%form{'data-bind' => 'submit: addFolder'}
  Add folder:
  %input{'data-bind' => 'value: newFolderName', 'placeholder'=>"Nome"}
  %button{type: "submit"}Adicionar

=content_for :script do
  :javascript

    function Folder(data) {
      data = data || {id: 0, name: "", description: ""};
      this.id = data.id;
      this.name = ko.observable(data.name);
      this.description = ko.observable(data.description);
    }

    function FolderListViewModel() {
      var self = this;
      self.folders = ko.observableArray([]);
      self.newFolderName = ko.observable();

      $.getJSON("/folders", function(allData) {
        var mappedFolders = $.map(allData, function(item) {
          return new Folder(item);
        });
        self.folders(mappedFolders);
      });

      self.addFolder = function() {
        self.folders.push(new Folder({name: self.newFolderName()}));
        self.newFolderName("");
      };

      self.removeFolder = function(folder) {
        self.folders.remove(folder);
      };

      self.save = function() {
        console.log(self.folders());
        $.ajax("/folders", {
          data: ko.toJSON({folders: self.folders}),
          type: "post",
          contentType: "application/json",
          success: function(result) {
            return console.log(result);
          }
        });
      };
    }

    $(function(){
      ko.applyBindings(new FolderListViewModel());
    });

Saving (independent if there are changes or not) always yield a similar request:

Started POST "/folders" for 127.0.0.1 at 2012-01-04 22:57:40 +0100
  Processing by FoldersController#create as */*
  Parameters: {"folders"=>[{"id"=>2, "name"=>"dim sum", "description"=>"ist warm!"}, {"id"=>3, "name"=>"Sushi", "description"=>"roh und kalt"}, {"id"=>1, "name"=>"Spagetti", "description"=>"Carbonara"}, {"id"=>10, "name"=>"Wiener", "description"=>"vom Kalb"}, {"id"=>11, "name"=>"Feijão", "description"=>""}], 
"folder"=>{}} <== LOOK HERE
  Folder Load (0.3ms)  SELECT "folders".* FROM "folders" ORDER BY "folders"."row_order"
   (0.1ms)  BEGIN
  Folder Load (0.2ms)  SELECT id, row_order FROM "folders" ORDER BY "folders"."row_order" DESC LIMIT 1
  Folder Load (0.2ms)  SELECT id, row_order FROM "folders" WHERE "folders"."row_order" = 8388592 LIMIT 1
  SQL (0.4ms)  INSERT INTO "folders" ("created_at", "description", "name", "row_order", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", Wed, 04 Jan 2012 21:57:40 UTC +00:00], ["description", nil], ["name", nil], ["row_order", 8388592], ["updated_at", Wed, 04 Jan 2012 21:57:40 UTC +00:00]]
   (0.5ms)  COMMIT
Redirected to http://0.0.0.0:3000/folders/21
Completed 302 Found in 54ms

Also deleted objects are only removed from the array and I wonder how rails should figure out, that it should strip them from the object store... everything is just a post... this looks all wrong to me.
What is my mistake?

Two bonus questions:
I dislike spamming my global js namespace with these constructor functions, but if I try to hide them inside an anonymous function, it seems ko does not find them anymore. Can this be remedied?

How can I tell rails globally, to stop redirecting me to html actions on json requests (how stupid is that anyways) and just send me an ok message or the errors?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沐歌 2024-12-31 15:59:29

对于全局变量,您可以通过为它们创建命名空间和/或将此页面的代码包装在代表视图模型的函数/对象中来解决此问题。例如:

var my = my || {}; // 你的命名空间。可能会在整个应用程序的一个地方定义它。

然后,您可以像平常一样定义视图模型,甚至将其包装在自调用函数中(如下所示)。我强烈推荐视图模型方法,因此页面的所有行为都挂在一个对象上。

(function (my, ko) {
    "use strict";
    my.viewmodel = {
        firstName: ko.observable(),
        lastName: ko.observable()
    };
}(my, ko));

For the global variables you can remedy that by creating a namespace for them and/or wrapping your code for this page in a function/object that represents your viewmodel. For example:

var my = my || {}; // your namespace. likely define this in one place for your entire app.

Then you can define your view model as you normally would, or even wrap it inside of a self invoking function (as shown below). I highly recommend the viewmodel approach, so all of your behavior for your page is hanging off one object.

(function (my, ko) {
    "use strict";
    my.viewmodel = {
        firstName: ko.observable(),
        lastName: ko.observable()
    };
}(my, ko));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文