JavaFX Model View ViewModel我应该在哪里实现任务?

时间:2016-03-08 05:55:09

标签: mvvm javafx task viewmodel worker

关于这个主题有几个教程和示例,但它们都只是一个类中的通用构建,以显示它是如何工作的。

所以我的问题是当我想遵循MVVM模式时,我必须实现我的所有任务?

鉴于以下内容:

型号:

class Model {

   /* When I place the Task here how can I deal with arguments and results from ViewController? */

   public BufferedImage bigTask (String this, String and, Image that){
       // Some code to build a BufferedImage
   }
}

视图模型:

class ViewController {

     private BufferedImage myBufferedImage;

     @FXML
     private Button aButton;



     /*Should I implement my Task here? But how I get information about progress? */

     final Task<Integer> myTask = new Task<Integer>(){

          @Override
          protected Integer call() throws Exception{

               updateProgress( // How to get here? Is it the right place? )

               return null;
          }

     };



     @FXML
     void setOnAction(ActionEvent actionEvent){

          myBufferedImage = Model.bigTask("this", "that", new Image("path"));

     }
}

希望我能解释一下这个问题。

提前致谢!

1 个答案:

答案 0 :(得分:0)

通常,您的任务应该在ViewModel中实现。 业务逻辑的实际实现应该在Model中完成,例如在服务类中完成。然后,ViewModel可以使用此服务并处理所有ui特定操作,例如为异步执行创建任务和更新进度值。但是,ViewModel可能不会直接更新ProgressIndicator,而是viewModel可能具有DoubleProperty&#34; progress&#34;在ViewModel中更新。在ViewController / CodeBehind中,将实际的ProgressIndicator绑定到ViewModel的此progress属性。这样,ViewModel独立于实际的UI控件,View不包含任何业务逻辑。

我认为你的例子有点特别。通常我会说&#34; BufferedImage&#34;是一个特定于ui的类,它只属于View而不是ViewModel,也不属于Model。但是,您的示例看起来像BufferedImage是业务操作的结果。在这种情况下,我将在ViewModel中创建一个ObjectProperty<BufferedImage>,并将任务也加载到ViewModel中。在你的ViewController中,我会为这个属性添加一个监听器,并在它改变时将图像放入ui。 这样,您的View类与图像的加载方式无关。