D
D
Dmitry Uvarov2016-04-16 19:57:36
JavaScript
Dmitry Uvarov, 2016-04-16 19:57:36

Is it possible to implement BEM into the popular MVC framework?

BEM-Comic-Characters.jpeg
The background of the question: I got acquainted with the methodology offered by BEM from Yandex (I read it several times, because of course it is written very "greatly", I looked at webinars, a spindle of holy posts), I tried, following the tutorial, to create a project, poked around to my heart's content and could not come to unambiguous opinion about its necessity (but this is a topic for holivars, we will omit it).
So, in fact, the question arose , how to use this miracle product with popular mvc frameworks (Angular, Backbone, Ember etc.)? How can the BEM project structure be related to the project structure in the same angular? And it's not just about their namespace convention, it's about delegating, declaring, moving blocks to other projects using not ENB, but let's say the same Gulp, etc.
After all, as far as I can judge from the description of the project (BEM), it has long grown into a separate framework with its own blackjack and plusses, but now there are just a dime a dozen of frameworks, and Google is still more solid than Yandex (although the translator in the latter works more cheerfully). How to be a novice developer? Maybe I'm missing details, I don't see the whole picture, or maybe the angle is not the right one, I would be grateful for your help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur, 2015-03-28
@timych

package application;

import java.awt.FileDialog;
import java.awt.Frame;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


// Тут необязательно наследоваться от JFrame
// Название класса  должно отображать его предназаначение
public class BookReader {

  // поля должны быть приватными
  private FileDialog fileDialog;
  private BookReaderCallback callback;

  // Вложенный интерфейс обратного вызова
  public interface BookReaderCallback {
    // метод будет вызван, когда текстовый файл будет успешно прочитан до конца
    void onReadComplete(String text);
  }

// В конструктор передаем фрейм родителя
// не обязательно его инстанцировать в этом классе
  public BookReader(Frame parent) {
    fileDialog = new FileDialog(parent, "Select book", FileDialog.LOAD);
  }

  //А название метода  должно отображать его действие или результат действия
  public void readBook() {

    // show() deprecated поэтому вызываем  "setVisible"
    fileDialog.setVisible(true);

    if (fileDialog.getDirectory() == null || fileDialog.getFile() == null) {
      return;
    }

    Scanner in = null;
    String text = "";
    try {
      in = new Scanner(new File(fileDialog.getDirectory(),
          fileDialog.getFile()));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    while (in.hasNext()) {
      text += in.nextLine() + "\n";
    }
    in.close();
    // прочитали файл и теперь через обьект класса обраьтного вызова 
    //нотифицируем вызывающий класс о том что текст прочитан и передаем ему результат
    if (callback != null) {
      callback.onReadComplete(text);
    }

  }

  //"ceттер" для экземпляра обратного вызова
  public void setCallback(BookReaderCallback callback) {
    this.callback = callback;
  }
}

package application;

import java.awt.Button;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;


public class JFrameCreator {

  public static void main(String[] args) {
    createGUI();
  }

  public static void createGUI() {

    try {
      UIManager.setLookAndFeel((LookAndFeel) Class.forName(UIManager.getCrossPlatformLookAndFeelClassName()).newInstance());
    } catch (InstantiationException | IllegalAccessException| ClassNotFoundException | UnsupportedLookAndFeelException e) {
      // Игнорируем
    }

    JPanel content = new JPanel(new FlowLayout());
    // вместо Label для текста стоит бы использовать TextArea(Label - для короткого однострочного текста),
    JTextArea textArea = new JTextArea();
    textArea.setText("Пока пусто...");
    Button btnOpenFileDialog = new Button("Browse");
    content.add(btnOpenFileDialog);
    content.add(textArea);

    JFrame frame = new JFrame("LIBRARY");
    frame.setContentPane(content);
    frame.setPreferredSize(new Dimension(300, 200));
    frame.pack();
    
    // центрируем относительно экрана
    frame.setLocationRelativeTo(null);

    // навешиваем слушатель на кнопку 
    // это плохой пример, скорее всего нужно навесить KeyListener, но лень имплементировать три метода
    btnOpenFileDialog.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        // создаем обьект BookReader
        BookReader bookReader = new BookReader(frame);
        // передаем ему экземпляр BookReaderCallback в виде анонимного класса
        bookReader.setCallback(new BookReader.BookReaderCallback() {

          // метод будет вызван из класса BookReader как только файл будет прочитан
          @Override
          public void onReadComplete(String text) {
            // меняем текст в Label
            textArea.setText(text);
          }
        });
        // запускаем "читалку" :)
        bookReader.readBook();

      }
    });

    frame.setVisible(true);
  }

}

If I understood the task correctly, then here's how it could be done approximately. This is all simplified of course (Yes, I'm not special in Swing).
And then again some kind of mess was written. Try to name classes and methods adequately in the first place. I already spoke about it by the way :).
And start with Java basics. It is noticeable that while the concept of OOP is bad.

A
Andrey Shishkin, 2015-11-24
@compiler

while(in.hasNext())
       s += in.nextLine() + "\r\n";

It is not good for a string to concatenate in a loop, it is not a mutable type. When you concatenate, a new object is created. As a result, you lose in performance. Use StringBuilder or StringBuffer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question